package group

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"go-admin/base/dao"
	"go-admin/base/ws"

	"go-admin/base/internal/svc"
	"go-admin/base/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewAddUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserLogic {
	return &AddUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AddUserLogic) AddUser(req *types.UserGroupSaveReqDTO) (resp *types.GroupBooleanRespDTOS, err error) {
	_, err = l.svcCtx.UserGroupModel.FindByGroupIdAndUserId(l.ctx, req.GroupId, req.UserId)
	if err != nil {
		if err != sqlc.ErrNotFound {
			_ = fmt.Errorf(err.Error())
			return nil, err
		}
	}
	l.svcCtx.UserGroupModel.Insert(l.ctx, &dao.UserGroup{
		GroupId: sql.NullInt64{
			Int64: req.GroupId,
			Valid: true,
		},
		UserId: sql.NullInt64{
			Int64: req.UserId,
			Valid: true,
		},
	})

	// 聊天服务器需要组中加入用户
	groupId := req.GroupId
	userId := req.UserId
	chatRoom := ws.RoomServer.ChatRooms[groupId]
	chatRoom.AddClient(userId)

	return &types.GroupBooleanRespDTOS{
		Data: true,
		Result: types.Result{
			Code: 200,
		},
	}, nil
}
